import { Component, OnInit, Input, HostBinding, Output, EventEmitter } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ReplaySubject } from 'rxjs';
import { ToasterService } from '../../services/toaster.service';

@Component({
  selector: 'm-image-preview',
  templateUrl: './image-preview.component.html',
  styleUrls: ['./image-preview.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: ImagePreviewComponent,
      multi: true,
    },
  ],
})
export class ImagePreviewComponent implements OnInit, ControlValueAccessor {
  constructor(private toaster: ToasterService) {}
  @Input() @HostBinding('class.disabled') disabled = false;
  @Input() control: HTMLInputElement;
  @Input() radius: string;
  @Input() saveBtn = false;
  @Input() set src(src: string) {
    this.preview.next(src);
  }
  @Output() saved = new EventEmitter<void>();

  @Input() valueType: 'file' | 'blob' = 'blob';
  file = new ReplaySubject<File>(1);

  preview = new ReplaySubject<string>(1);
  touche = new ReplaySubject<boolean>(1);
  change: (path: string) => void;
  ngOnInit() {
    this.control.hidden = true;
    this.control.addEventListener('change', () => {
      this.selected(this.control)
      this.saveBtn = true;
    });
  }
  click() {
    this.control.click();
  }
  onSave() {
    this.saved.emit();
    this.saveBtn = false;
  }
  selected(input: HTMLInputElement) {
    this.touche.next(true);
    this.preview.next('');
    if (!input || !input.files.length) {
      return;
    }
    this.file.next(null);
    if (input.files[0].size > 1024 * 1024 * 2) {
      this.toaster.warn('图片文件不能大于2M');
      input.value = '';
      return;
    }
    const src = URL.createObjectURL(input.files[0]);
    const img = new Image();
    img.src = src;
    img.onerror = () => {
      input.value = '';
      this.toaster.warn('不支持的图片格式');
    };
    img.onload = () => {
      this.file.next(input.files[0]);
      this.preview.next(src);
    };
  }

  writeValue(obj: any): void {
    this.preview.next(obj);
  }
  registerOnChange(fn: any): void {
    if (this.valueType === 'blob') {
      this.preview.subscribe(fn);
    } else if (this.valueType === 'file') {
      this.file.subscribe(fn);
    }
  }
  registerOnTouched(fn: any): void {
    this.touche.subscribe(fn);
  }
  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
}
